package com.scm.utils;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.scm.core.bean.exp.UfdmException;

/**
 * 上传文件工具类
 * 
 * @author Young
 * @Date 2016.11.15
 */
public class UploadAndDownUtil {

	private static String filePath;

	static {
		Properties p = new Properties();
		try {
			p.load(UploadAndDownUtil.class.getClassLoader().getResourceAsStream("config.properties"));
			filePath = p.getProperty("uploadPath");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 保存用户上传的文件
	 * 
	 * @param file
	 *            上传的文件
	 * @param directory
	 *            文件存储路径 "abc"
	 * @return 返回文件路径
	 * @throws UfdmException 
	 * @throws Exception
	 */
	public static String uploadFile(MultipartFile file, String directory) throws UfdmException {
		if (file != null && !file.isEmpty()) {
			try {
				String originName = file.getOriginalFilename();
				String fileType = originName.substring(originName.lastIndexOf("."));
				Long time=System.currentTimeMillis();
				String path = filePath + File.separator + "file" + File.separator + directory
						+ File.separator + time + fileType;
				File f = createFile(path);
				file.transferTo(f);
				return "/file/"+directory
						+ "/" + time + fileType;
			} catch (Exception e) {
				e.printStackTrace();
				throw new UfdmException("上传文件失败");
			}
		}
		return "";
	}

	public static File createFile(String path) throws IOException {
		File f = new File(path);
		if (!f.getParentFile().exists())
			f.getParentFile().mkdirs();
		if (!f.exists())
			f.createNewFile();
		return f;
	}

	/**
	 * 保存用户上传的图片
	 * 
	 * @param file
	 *            上传的文件
	 * @param directory
	 *            文件存储路径 "abc"
	 * @return 返回文件路径
	 * @throws UfdmException 
	 * @throws Exception
	 */
	public static String uploadImage(MultipartFile file, String directory) throws UfdmException {
		if (file != null && !file.isEmpty()) {
			try {
				String originName = file.getOriginalFilename();
				String fileType = originName.substring(originName.lastIndexOf("."));
				Long time=System.currentTimeMillis();
				String path = filePath +File.separator+"image"+ File.separator + directory +  File.separator
						+ time + fileType;
				File f = createFile(path);
				file.transferTo(f);
				return "/image"+"/"+directory +  "/"
						+ time + fileType;
			} catch (Exception e) {
				e.printStackTrace();
				throw new UfdmException("上传图片失败");
			}
		}
		return "";
	}


	/**
	 * 文件下载
	 * 
	 * @param filename
	 *            文件名
	 * @param parentName
	 *            文件的父文件名
	 * @param res
	 * @throws UfdmException 
	 * @throws IOException
	 */
	public static void downFile(String originName, String filename, HttpServletRequest req, HttpServletResponse res) throws UfdmException {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(
					new FileInputStream(filePath + filename));
			bos = new BufferedOutputStream(res.getOutputStream());

			long fileLength = new File(filePath + filename).length();

			res.setCharacterEncoding("UTF-8");
			res.setContentType("multipart/form-data");
			/*
			 * 解决各浏览器的中文乱码问题
			 */
			//String userAgent = req.getHeader("User-Agent");
			//byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
			byte[] bytes=originName.getBytes("utf-8");
			originName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			res.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", originName));

			res.setHeader("Content-Length", String.valueOf(fileLength));
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new UfdmException("文件下载失败");
		} finally {
			try {
				if (bis != null)
					bis.close();
				if (bos != null)
					bos.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 删除附件
	 * 
	 * @param parentName
	 * @param filename
	 */
	public static void removeFile(String filename) {
		File file = new File(filePath + filename);
		file.delete();
	}
	
	public static String getAbsolutePath(String filename){
		return filePath + filename;
	}
	
	/**
	 * 生成pdf文件
	 * @param prefix
	 * @param request
	 * @param response
	 * @throws UfdmException
	 */
	public static void expoprtPdf(String prefix,MultipartHttpServletRequest request, HttpServletResponse response) throws UfdmException{
		String id=request.getParameter("id");
		String filePath = UploadAndDownUtil.getAbsolutePath(prefix+id+".pdf");
		String imagePath = UploadAndDownUtil.getAbsolutePath(prefix+id+".png");
		Document document = new Document(PageSize.A4, 10, 10, 10, 10);
		try {
			File pdf=UploadAndDownUtil.createFile(filePath);
			File png=UploadAndDownUtil.createFile(imagePath);
			MultipartFile mfile = request.getFile("imgData"); // 获取数据
			InputStream file = mfile.getInputStream();
			byte[] fileByte = FileCopyUtils.copyToByteArray(file);
			FileImageOutputStream imageOutput = new FileImageOutputStream(png);// 打开输入流
			imageOutput.write(fileByte, 0, fileByte.length);// 生成本地图片文件
			imageOutput.close();

			PdfWriter.getInstance(document, new FileOutputStream(pdf)); // itextpdf文件
			document.open();
			BufferedImage bi = ImageIO.read(new File(imagePath));
			int destWidth = (int) PageSize.A4.getWidth(); // 切片宽度
			int destHeigth = (int) PageSize.A4.getHeight(); // 切片高度
			int srcWidth = bi.getWidth();
			int srcHeigth = bi.getHeight();
			Image image = bi.getScaledInstance(srcWidth, srcHeigth, Image.SCALE_DEFAULT);
			int cols = 0;// 切片横向向数量
			if (srcHeigth % destHeigth == 0) {
				cols = (int) (srcHeigth / destHeigth);
			} else {
				cols = (int) Math.floor(srcHeigth / destHeigth) + 1;
			}
			// 横向循环切图片
			for (int i = 0; i < cols-1; i++) {
				ImageFilter cropFilter;
				Image ig;
				cropFilter = new CropImageFilter(0, i * (destHeigth-20), destWidth+310, destHeigth);
				ig = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
				BufferedImage tag = new BufferedImage(destWidth+310, destHeigth, BufferedImage.TYPE_INT_ARGB_PRE);
				Graphics g = tag.getGraphics();
				g.drawImage(ig, 0, 0, null); // 绘制缩小后的图
				g.dispose();

				// 输出为文件
				String imgFilePath = UploadAndDownUtil.getAbsolutePath(prefix+"temp" + i + ".png");
				File imgFile=UploadAndDownUtil.createFile(imgFilePath);
				ImageIO.write(tag, "png", imgFile);
				com.itextpdf.text.Image img1 = com.itextpdf.text.Image.getInstance(imgFilePath);
				// 设置图片宽高
				img1.scaleAbsolute(PageSize.A4.getWidth()-10, img1.getHeight());
				// 居中
				img1.setAlignment(com.itextpdf.text.Image.MIDDLE);
				// 另起一页
				document.newPage();
				document.add(img1);
				if (imgFile.exists()) {
					imgFile.delete();
				}
			}
			document.close();
			png.delete();
		} catch (Exception e) {
			e.printStackTrace();
			throw new UfdmException("产生PDF失败");
		}
	}
	
	/**
	 * 复制图片
	 * @param filename
	 * @param directory
	 * @return
	 * @throws UfdmException
	 */
	public static String copyImage(String filename,String directory) throws UfdmException{
		BufferedInputStream bis=null;
		BufferedOutputStream bos=null;
		try {
			File file=new File(filePath+filename);
			bis=new BufferedInputStream(new FileInputStream(file));
			String fileType = filename.substring(filename.lastIndexOf("."));
			Long time=System.currentTimeMillis();
			String path = filePath + File.separator + "image" + File.separator + directory
					+ File.separator + time + fileType;
			File f = createFile(path);
			bos=new BufferedOutputStream(new FileOutputStream(f));
			int len=-1;
			byte[] buf=new byte[2048];
			while((len=bis.read(buf))!=-1){
				bos.write(buf,0,len);
			}
			return "/image/"+directory
					+ "/" + time + fileType;
		} catch (Exception e) {
			e.printStackTrace();
			throw new UfdmException("复制文件失败");
		}finally{
			try {
				if(bos!=null) bos.close();
				if(bis!=null) bis.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
}
